package com.yupi.project.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yupi.project.model.AuthenticatorResult;
import com.yupi.project.model.ProtectedRequest;
import com.yupi.project.model.RequestHolder;
import com.yupi.project.model.RequestInfo;
import com.yupi.project.security.SecurityVerificationHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static com.yupi.yuapicommon.utils.SignUtils.getSign;

/**
 * @description: 数字签名认证
 * @author SummerBird
 * @date 2024/3/8 19:33
 * @version 1.0
 */
@Component
@Slf4j
public class AuthenticationHandler implements SecurityVerificationHandler {
    @Override
    public AuthenticatorResult auth(ProtectedRequest protectedRequest) {
        RequestInfo requestInfo = RequestHolder.get();
        String accessKey = requestInfo.getAccessKey();
        String nonce = requestInfo.getNonce();
        String timestamp = requestInfo.getTimestamp();
        String sign = requestInfo.getSign();
        RequestInfo.UserInfo invokeUser = requestInfo.getUserInfo();
        // 构建参数
        Map<String, String> hashMap = new HashMap<>(4);
        hashMap.put("accessKey",accessKey);
        hashMap.put("timestamp",timestamp);
        hashMap.put("nonce",nonce);
//        hashMap.put("body",body);
        //secretKey从数据库中拿出
        String secretKey = invokeUser.getSecretKey();
        String serverSign = getSign(hashMap, secretKey);
        // 签名认证
        if(StringUtils.isBlank(sign) || !sign.equals(serverSign)){
            return AuthenticatorResult.fail("没有权限");
        }
        return AuthenticatorResult.success();
    }

    @Override
    public int getOrder() {
        return 13;
    }
}
